package com.cc.sanjieduan.events.listeners;

import com.cc.sanjieduan.events.UserLoginEvent;
import com.cc.sanjieduan.mapper.UserOnlineMapper;
import com.cc.sanjieduan.pojo.BaseUser;
import com.cc.sanjieduan.pojo.User;
import com.cc.sanjieduan.pojo.UserOnline;
import com.cc.sanjieduan.service.UserService;
import com.cc.sanjieduan.utils.RequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.security.authentication.event.AbstractAuthenticationFailureEvent;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Component
public class UserloginListener {

    private UserService userService;

    private UserOnlineMapper userOnlineMapper;

    @Autowired
    public void setUserOnlineMapper(UserOnlineMapper userOnlineMapper) {
        this.userOnlineMapper = userOnlineMapper;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @EventListener
    public void onLoginSuccess(AuthenticationSuccessEvent loginEvent) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //BaseUser baseUser = SecurityUtils.getUser();
        //获取当前登录的用户
        BaseUser baseUser = (BaseUser) loginEvent.getAuthentication().getPrincipal();
        CompletableFuture.runAsync(() -> {//runAsync是不需要结果的异步
            try {
                User user = new User();
                user.setUId(baseUser.getUserId());
                //  Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//存放了是请求的系统和软件信息
                String ip = RequestUtil.getRemoteHost(request);//获取到用户的ip
                //  user.setLastLogin(user.getCurrentLogin());
                user.setCurrentLogin(new Date());
                // user.setLastLoginIp(user.getCurrentLoginIp());
                user.setCurrentLoginIp(ip);
                userService.updateUserLogin(user);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
        CompletableFuture.runAsync(() -> {
            try {
                Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//存放了是请求的系统和软件信息
                String ip = RequestUtil.getRemoteHost(request);//获取到用户的ip
                UserOnline userOnline = new UserOnline();
                userOnline.setSessionId(request.getSession().getId());
                userOnline.setLoginName(baseUser.getUsername());
                userOnline.setStartTimestamp(new Date());
                userOnline.setStatus("1");//设置为在线
                userOnline.setIpaddr(ip);
                userOnline.setLoginLocation(RequestUtil.getLocationByIp(ip));//请求第三方服务器,需要时间,所以应该放到单独的线程中执行
                userOnline.setOs(osAndBrowserInfo.get("os"));
                userOnline.setBrowser(osAndBrowserInfo.get("browser"));
                userOnline.setExpireTime(30L);
                //保存到数据库,发现有问题,当前用户的数据如果已经存在了 应该更新
                UserOnline currentLogin = userOnlineMapper.selectByLoginName(baseUser.getUsername());//先查询一下
                if (currentLogin != null) {
                    //存在,删除
                    userOnlineMapper.deleteByLoginName(baseUser.getUsername());
                }
                userOnlineMapper.addOnlineData(userOnline);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }


    @EventListener
    public void onLoginFail(AbstractAuthenticationFailureEvent failureEvent) {
        System.err.println("UserloginListener中的方法onLoginFail 执行了");
    }

//
//
//    /**
//     * 更新用户的基本登录信息
//     *
//     * @param loginEvent
//     */
//    @EventListener
//    // @Async
//    public void upDateUserInfo(UserLoginEvent loginEvent) {
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        BaseUser baseUser = SecurityUtils.getUser();
//        //通过异步执行当前操作,内部有自己的线程池
//        CompletableFuture.runAsync(() -> {//runAsync是不需要结果的异步
//            try {
//                User user = new User();
//                user.setUId(baseUser.getUserId());
//                //  Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//存放了是请求的系统和软件信息
//                String ip = RequestUtil.getRemoteHost(request);//获取到用户的ip
//                //  user.setLastLogin(user.getCurrentLogin());
//                user.setCurrentLogin(new Date());
//                // user.setLastLoginIp(user.getCurrentLoginIp());
//                user.setCurrentLoginIp(ip);
//                userService.updateUserLogin(user);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
////        new Thread() {
////            @Override
////            public void run() {
////                try {
////                    //  Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//存放了是请求的系统和软件信息
////                    String ip = RequestUtil.getRemoteHost(request);//获取到用户的ip
////                    //  user.setLastLogin(user.getCurrentLogin());
////                    user.setCurrentLogin(new Date());
////                    // user.setLastLoginIp(user.getCurrentLoginIp());
////                    user.setCurrentLoginIp(ip);
////                    userService.updateUserLogin(user);
////                } catch (Exception e) {
////                    e.printStackTrace();
////                }
////            }
////        }.start();
//    }
//
//    /**
//     * 更新用户的在线状态
//     *
//     * @param loginEvent
//     */
//    @EventListener
//    //@Async
//    public void upDateUserOnline(UserLoginEvent loginEvent) {
//        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        BaseUser user = SecurityUtils.getUser();
//
//        CompletableFuture.runAsync(() -> {
//            try {
//                Map<String, String> osAndBrowserInfo = RequestUtil.getOsAndBrowserInfo(request);//存放了是请求的系统和软件信息
//                String ip = RequestUtil.getRemoteHost(request);//获取到用户的ip
//                UserOnline userOnline = new UserOnline();
//                userOnline.setSessionId(request.getSession().getId());
//                userOnline.setLoginName(user.getUsername());
//                userOnline.setStartTimestamp(new Date());
//                userOnline.setStatus("1");//设置为在线
//                userOnline.setIpaddr(ip);
//                userOnline.setLoginLocation(RequestUtil.getLocationByIp(ip));//请求第三方服务器,需要时间,所以应该放到单独的线程中执行
//                userOnline.setOs(osAndBrowserInfo.get("os"));
//                userOnline.setBrowser(osAndBrowserInfo.get("browser"));
//                userOnline.setExpireTime(30L);
//                //保存到数据库,发现有问题,当前用户的数据如果已经存在了 应该更新
//                UserOnline currentLogin = userOnlineMapper.selectByLoginName(user.getUsername());//先查询一下
//                if (currentLogin != null) {
//                    //存在,删除
//                    userOnlineMapper.deleteByLoginName(user.getUsername());
//                }
//                userOnlineMapper.addOnlineData(userOnline);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        });
//
//    }

    /**
     * 更新登陆日志
     *
     * @param loginEvent
     */
    @EventListener
    //@Async
    public void onLoginLog(UserLoginEvent loginEvent) {
        //TODO 交给你们写
    }
}
